/**
 * Copyright (C) 2011-2012 Luca Li Greci
 *
 * This file is part of pojo-creator
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.pojocreator.provider.collection;

import org.apache.commons.collections.CollectionUtils;

/**
 * The SequentialFromCollection implements the required method
 * {@link com.pojocreator.provider.DataProvider#data()} to provide a value from a given array of
 * elements.
 * <p>
 * The element returned is the next one available in the array, if the last has
 * already been extracted than the first in the sequence will be available.
 * 
 * @author Luca Li Greci
 * 
 * @param <T> Data type to provide
 */
public class SequentialFromCollection < T > extends AbstractFromCollection < T > {
    private int index;

    /**
     * Creates a DataProvider using the element in the collection
     * 
     * @param values array of elements type T
     */
    public SequentialFromCollection(T... values) {
        super(values);
        index = -1;
    }

    /**
     * This method returns an element from the array of elements passed in. The
     * underlying data structure is treated as a circular buffer so when the last
     * element is extracted the next one will be the first in the collection.
     * <p>
     * <b>N.B.</b> This method can return null if the array of elements is null
     * or empty.
     * 
     * @return an element from the array, when the last element is extracted the
     *         next one will be the first in the data set.
     */
    @Override
    public T data() {
        if (CollectionUtils.isEmpty(values)) {
            return null;
        }
        index++;
        index %= values.size();
        return values.get(index);
    }

}
